//
//  XSCustomTaskViewController.m
//  XSDownloadDemo
//
//  Created by 大帅 on 2024/1/9.
//

#import "XSCustomTaskViewController.h"

@interface XSCustomTaskViewController ()
/** url输入框 */
@property (nonatomic, strong) UITextField *urlField;
/** 视频名字 */
@property (nonatomic, strong) UITextField *videoNameField;
/** 添加自定义下载地址按钮 */
@property (nonatomic, strong) UIButton *addBtn;


@end

@implementation XSCustomTaskViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"M3u8 - Custom";
    self.view.backgroundColor = UIColor.orangeColor;
    
    [self createViewUI];
    
}

-(void)createViewUI {
    
    [self.view addSubview:self.urlField];
    [self.urlField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view).offset(15);
        make.right.mas_equalTo(self.view).offset(-15);
        make.top.mas_equalTo(self.view).offset(GK_STATUSBAR_NAVBAR_HEIGHT + 20);
        make.height.mas_greaterThanOrEqualTo(50);
    }];
    
    [self.view addSubview:self.videoNameField];
    [self.videoNameField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.urlField);
        make.top.equalTo(self.urlField.mas_bottom).offset(20);
        make.height.mas_greaterThanOrEqualTo(50);
    }];
    
    [self.view addSubview:self.addBtn];
    [self.addBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.videoNameField.mas_bottom).offset(40);
        make.height.mas_equalTo(50);
        make.width.mas_equalTo(200);
    }];
}

-(UITextField *)urlField {
    if (!_urlField) {
        _urlField = [[UITextField alloc] init];
        _urlField.placeholder = @"请输入下载url";
        _urlField.textColor = UIColor.redColor;
        _urlField.font = [UIFont systemFontOfSize:15];
        _urlField.clearButtonMode = UITextFieldViewModeAlways;
        _urlField.backgroundColor = UIColor.cyanColor;
    }
    return _urlField;
}

-(UITextField *)videoNameField {
    if (!_videoNameField) {
        _videoNameField = [[UITextField alloc] init];
        _videoNameField.placeholder = @"请输入你中意的视频名称";
        _videoNameField.textColor = UIColor.redColor;
        _videoNameField.font = [UIFont systemFontOfSize:15];
        _videoNameField.clearButtonMode = UITextFieldViewModeAlways;
        _videoNameField.backgroundColor = UIColor.cyanColor;
    }
    return _videoNameField;
}
 
-(UIButton *)addBtn {
    if (!_addBtn) {
        _addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_addBtn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        _addBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_addBtn setTitle:@"确定" forState:UIControlStateNormal];
        [_addBtn setBackgroundColor:UIColor.redColor];
        [_addBtn addTarget:self action:@selector(clickAddBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _addBtn;
}

-(void)clickAddBtn {
    
    if (![[XSDownloadManagerM3u8 sharedManager] netWorkAllowDownloadTask]) {
        [[XSToastView shareManager] showMessage:@"当前无网络"];
        return;
    }
    
    if ([self trimEmpty:self.urlField.text]) {
        [[XSToastView shareManager] showMessage:@"请输入下载地址"];
        return;
    }
    if ([self trimEmpty:self.videoNameField.text]) {
        [[XSToastView shareManager] showMessage:@"请输入自定义视频名称"];
        return;
    }
    
    NSArray *list = [[XSDataSaveManager sharedManager] lookDownloadAllData];
    
    int i = 0;
    if (list.count > 0) {
        XSTestModel *lastModel = list.lastObject;
        i = lastModel.videoId.intValue - 300 + 1;
        
        // 防止重复下载
        for (int k = 0; k < list.count; k ++) {
            XSTestModel *mod = [list objectAtIndex:k];
            if ([mod.url isEqualToString: self.urlField.text]) {
                [[XSToastView shareManager] showMessage:@"当前视频已加入下载列表"];
                self.urlField.text = @"";
                self.videoNameField.text = @"";
                return;
            }
        }
    }
        
    XSTestModel *model = [[XSTestModel alloc] init];
    model.url       = self.urlField.text;
    model.videoName = self.videoNameField.text;
    model.videoId   = [NSString stringWithFormat:@"%d", i + 300];
    [[XSDownloadManagerM3u8 sharedManager] addDownloadingTask:model];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[XSToastView shareManager] showMessage:@"当前视频已加入下载列表"];
        [self.navigationController popViewControllerAnimated:YES];
    });
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.urlField resignFirstResponder];
    [self.videoNameField resignFirstResponder];
}

// 检查字符串是否为空
- (BOOL)trimEmpty:(NSString *)str {
    if (!str) {
        return YES;
    }
    if ([str isKindOfClass:[NSNull class]]) {
        return YES;
    }
    NSString *trimStr = [[NSString stringWithFormat:@"%@",str] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if([trimStr isEqualToString:@"(null)"] || [trimStr isEqualToString:@"null"]) {
        return YES;
    }
    return (trimStr == nil || trimStr.length <= 0);
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
